package com.fjwt.gz.sync.notify;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 外部供应商通知接口
 */

@RestController
@Slf4j
@RequestMapping("/api/outSide/Supplier")
public class OutSideSupplierNotify {
    private static final String logPrefix = "【洋芋网络】";

    @Autowired
    private AwardVirtualSupplierService awardVirtualSupplierService;
    @Autowired
    private AwardVirtualOutsideService awardVirtualOutsideService;
    @Autowired
    private FansOrderVirtualService fansOrderVirtualService;
    @Autowired
    private AwardVirtualInsideService awardVirtualInsideService;
    @Autowired
    private AwardVirtualService virtualAwardService;
    @Autowired
    private ScoreExchangeService scoreExchangeService;
    @Autowired
    private FansAwardService fansAwardService;

    /**
     * 商品推送通知
     * @return
     */
    @PostMapping("/yangyuwangluo/goods/notify")
    @Transactional
    public String goodsNotify(HttpServletRequest request) {
        log.info("{}外部供应商商品推送通知", logPrefix);
        Map<String, Object> body = this.getBody(request);
        JSONObject reqJson = JSONObject.parseObject(JSONObject.toJSONString(body));
        log.info("商品详情：{}", JSONUtil.toJsonStr(reqJson));

        // 查询供应商id
        AwardVirtualSupplierEntity awardVirtualSupplierEntity = awardVirtualSupplierService.getOne(AwardVirtualSupplierEntity.gw().eq(AwardVirtualSupplierEntity::getSupplierName, "yangyuwangluo"));

        String thirdGoodsId = reqJson.getString("goodsid");
        // 查询商品是否存在
        LambdaQueryWrapper<AwardVirtualOutsideEntity> gw = AwardVirtualOutsideEntity.gw()
                .eq(AwardVirtualOutsideEntity::getThirdGoodsId, thirdGoodsId)
                .eq(AwardVirtualOutsideEntity::getVirtualSupplierId, awardVirtualSupplierEntity.getVirtualSupplierId());
        List<AwardVirtualOutsideEntity> goodsOutsideEntityList = awardVirtualOutsideService.list(gw);

        if (ObjectUtils.isEmpty(goodsOutsideEntityList)) {
            return "error";
        }
        AwardVirtualOutsideEntity virtualGoodsOutsideEntity = goodsOutsideEntityList.get(0);

        Integer goodsPrice = reqJson.getBigDecimal("goodsprice").multiply(new BigDecimal("100")).intValue();
        Integer status = reqJson.getInteger("goodsstatus");
        // 判断商品状态
        if (404 == status) {
            virtualGoodsOutsideEntity.setState(2);
        }else {
            virtualGoodsOutsideEntity.setState(status);
        }
        // 商品状态或者价格变动下架商品
        if (0 == virtualGoodsOutsideEntity.getState() || 2 == virtualGoodsOutsideEntity.getState() || !Objects.equals(virtualGoodsOutsideEntity.getGoodsPrice(), goodsPrice)) {
            // 虚拟奖品表
            List<AwardVirtualInsideEntity> goodsInsideEntityList = awardVirtualInsideService.list(AwardVirtualInsideEntity.gw().eq(AwardVirtualInsideEntity::getVirtualOutsideId, virtualGoodsOutsideEntity.getVirtualOutsideId()));
            if (ObjectUtils.isNotEmpty(goodsInsideEntityList)) {
                List<Long> insideGoodsIdList = goodsInsideEntityList.stream().map(AwardVirtualInsideEntity::getVirtualInsideId).collect(Collectors.toList());
                if (ObjectUtils.isNotEmpty(insideGoodsIdList)) {
                    List<AwardVirtualEntity> virtualAwardEntityList = virtualAwardService.list(AwardVirtualEntity.gw().in(AwardVirtualEntity::getVirtualInsideId, insideGoodsIdList));
                    if (ObjectUtils.isNotEmpty(virtualAwardEntityList)) {
                        for (AwardVirtualEntity virtualAwardEntity : virtualAwardEntityList) {
                            virtualAwardEntity.setState(1);
                            virtualAwardService.updateById(virtualAwardEntity);
                        }
                        List<Long> virtualAwardIds = virtualAwardEntityList.stream().map(AwardVirtualEntity::getVirtualId).collect(Collectors.toList());
                        // 权益商城表
                        List<ScoreExchangeEntity> scoreExchangeEntityList = scoreExchangeService.list(ScoreExchangeEntity.gw().in(ScoreExchangeEntity::getAwardId, virtualAwardIds).eq(ScoreExchangeEntity::getAwardType, 2));
                        if (ObjectUtils.isNotEmpty(scoreExchangeEntityList)) {
                            for (ScoreExchangeEntity scoreExchangeEntity : scoreExchangeEntityList) {
                                scoreExchangeEntity.setIsFlag(1);
                                scoreExchangeService.updateById(scoreExchangeEntity);
                            }
                        }
                    }
                }
            }
        }
        virtualGoodsOutsideEntity.setGoodsName(reqJson.getString("goodsname"));
        virtualGoodsOutsideEntity.setGoodsPrice(goodsPrice);
        virtualGoodsOutsideEntity.setType(reqJson.getInteger("goodstype"));

        awardVirtualOutsideService.updateById(virtualGoodsOutsideEntity);

        return "ok";
    }

    /**
     * 订单推送通知
     * @return
     */
    @Transactional
    @PostMapping("/yangyuwangluo/order/notify")
    public String orderNotify(HttpServletRequest request) {
        log.info("{}外部商品订单推送通知", logPrefix);
        Map<String, Object> body = this.getBody(request);
        JSONObject reqJson = JSONObject.parseObject(JSONObject.toJSONString(body));
        log.info("订单详情：{}", reqJson.toJSONString());

        String orderNo = reqJson.getString("usorderno");
        FansOrderVirtualEntity fansOrderVirtualEntity = fansOrderVirtualService.getById(orderNo);
        if (ObjectUtils.isEmpty(fansOrderVirtualEntity)) {
            return "error";
        }

        fansOrderVirtualEntity.setThirdOrderNo(reqJson.getString("orderno"));
        fansOrderVirtualEntity.setState(reqJson.getInteger("status"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("receipt", reqJson.getString("receipt"));
        if (4 == fansOrderVirtualEntity.getState()) {
            jsonObject.put("refundstatus", reqJson.getInteger("refundstatus"));
            jsonObject.put("refundreceipt", reqJson.getString("refundreceipt"));
            jsonObject.put("cardlist", reqJson.getString("cardlist"));
        }
        fansOrderVirtualEntity.setReceipt(jsonObject.toJSONString());

        fansOrderVirtualService.updateById(fansOrderVirtualEntity);

        FansAwardEntity fansAwardEntity = fansAwardService.getById(fansOrderVirtualEntity.getFansAwardId());
        if (5 == fansOrderVirtualEntity.getState()) {
            fansAwardEntity.setState(1);
            fansAwardEntity.setActivateTime(new Date());
        }else if (4 == fansOrderVirtualEntity.getState()) {
            fansAwardEntity.setState(4);
        }
        fansAwardService.updateById(fansAwardEntity);
        return "ok";
    }


    protected final Map<String, Object> getBody(HttpServletRequest request) {
        try {
            Map map = new HashMap<String, String>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Object key : parameterMap.keySet()) {
                map.put(key.toString(), ((String[]) parameterMap.get(key))[0]);
            }
            log.info(logPrefix + "解析参数返回的信息是：{}", JSONUtil.toJsonStr(map));
            return map;
        } catch (Exception e) {
            log.error("请求头部取数据异常：{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
    }
}
